package com.whfc.wxmp.shiro;

import com.whfc.common.util.SessionAttr;
import com.whfc.wxmp.annotation.CurrentWxUser;
import com.whfc.fuum.entity.WxUser;
import com.whfc.fuum.dto.WxUserToken;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

/**
 * @Description:
 * @author: xugcheng
 * @version: 1.0
 * @date: 2019/7/22 11:14
 */
public class WxMpRealm extends AuthorizingRealm {

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        if (token instanceof WxUserToken) {
            WxUserToken wxUserToken = (WxUserToken) token;
            WxUser wxUser = wxUserToken.getWxUser();
            SecurityUtils.getSubject().getSession().setAttribute(SessionAttr.WXMP_USER, wxUser);
            AuthenticationInfo authcInfo = new SimpleAuthenticationInfo(wxUser.getOpenId(), wxUser.getOpenId(), this.getName());
            return authcInfo;
        }
        return null;
    }

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof WxUserToken || token instanceof AuthenticationToken;
    }
}
